import numpy as np
import matplotlib.pyplot as plt
import time
import sys
import math as m
import xlrd


def plot():

    plt.ion()

    for i in range(100000):
        y = np.random.random()
        x = np.random.random()
        plt.scatter(x, y)
        # plt.draw()
    plt.pause(1e-5)
    if not plt.get_fignums():
        sys.exit()


def cal_dist_matrix(file):

    # 经度
    x = []
    y = []
    dist = []

    wb = xlrd.open_workbook(filename=file)  # 打开文件
    print(wb.sheet_names())  # 获取所有表格名字

    sheet1 = wb.sheet_by_index(0)  # 通过索引获取表格
    print(sheet1.name, sheet1.nrows, sheet1.ncols)

    x = sheet1.col_values(0)
    y = sheet1.col_values(1)  # 获取列内容

    print(x)
    print(y)

    dist = np.zeros([len(x), len(x)], dtype=float)
    print(dist)

    # for i in range(10):
    lenx = len(x)
    for i in range(lenx):
        for j in range(lenx):
            try:
                dist[i, j] = m.sqrt((x[i]-x[j])**2+(y[i]-y[j])**2)
            except:
                print("************ERROR*************")
        print(i)

    np.savetxt(
        'E:/codes/courses/ArtificialIntelligence/GA/tsp_ga/dist.txt', dist, fmt='%0.8f')


# cal_dist_matrix("E:/codes/courses/ArtificialIntelligence/GA/raw eil101.xlsx")

def get_dist_matrix(file):
    dist = np.loadtxt(
        file, delimiter=' ')
    return dist


# dist = get_dist_matrix(
#     "E:/codes/courses/ArtificialIntelligence/GA/tsp_ga/dist.txt")
# print(dist[0][1],dist[0][2])

